package com.example.permission.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.example.permission.common.CommonParam;
import com.example.permission.common.Constants;
import com.example.permission.common.result.Result;
import com.example.permission.common.utils.NetworkUtil;
import com.example.permission.entity.dto.LoginDTO;
import com.example.permission.service.SysLoginLogService;
import com.example.permission.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description： 登陆
 * @author: xuwq
 * @date: 2020/5/9 17:22
 */
@RestController
@Api(tags = "登陆")
public class LoginController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SysLoginLogService sysLoginLogService;

    @GetMapping("v1/getAuthCodeImg")
    @ApiOperation("图形验证码")
    @SneakyThrows
    public void getAuthCodeImg(HttpServletRequest request, HttpServletResponse response) {
        //定义图形验证码的长和宽  码值个数  干扰圈数
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(90, 40, 4, 5);
        BufferedImage codeImg = circleCaptcha.getImage();
        String code = circleCaptcha.getCode();
        String ipAddress = NetworkUtil.getIpAddress(request);
        redisTemplate.opsForValue().set(Constants.IMG_IDENTIFY_CODE + ipAddress, code, 3, TimeUnit.MINUTES);
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(codeImg, "jpeg", sos);
    }

    @PostMapping("v1/login")
    @ApiOperation(value = "登陆")
    public Result<Map<String, Object>> queryListByPage(@RequestBody @Valid LoginDTO loginDTO) {
        return this.sysUserService.login(loginDTO);
    }

    @GetMapping("v1/logout")
    @ApiOperation("后台登出")
    public Result logout() {
        String key = Constants.USER_TOKEN + CommonParam.getInstance().getUserNo();
        String token = (String) redisTemplate.opsForValue().get(key);
        sysLoginLogService.updateLogoutTime(CommonParam.getInstance().getUserNo());
        if (token != null) {
            redisTemplate.delete(key);
        }
        return Result.success();
    }
}
